package com.szholly.plug.form.controller;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.StringUtils;
import com.szholly.utils.util.TreeDataNode;
import com.szholly.data.common.util.TablesUtils;
import com.szholly.data.general.Field;
import com.szholly.data.general.GlobalDataType;
import com.szholly.data.general.ITable;
import com.szholly.data.general.ITableFactory;
import com.szholly.data.general.ITableInfo;
import com.szholly.data.general.IWorkspace;
import com.szholly.data.general.IWorkspaceFactory;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 定义表单构建控件器
 */
@Controller
public class BuilderController {

	/**
	 * 获取当前的系统表集
	 * 
	 * @param req
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/builder/getTables")
	public void getTables(HttpServletRequest req, HttpServletResponse response)
			throws IOException {
		List<TreeDataNode> result = TablesUtils.getTables();
		JSONArray arrayObject = JSONArray.fromObject(result);
		String returnValue = arrayObject.toString();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		OutputStream stream = response.getOutputStream();
		stream.write(returnValue.getBytes("UTF-8"));
	}

	/**
	 * 获取数据库中的所有表(原始)
	 * 
	 * @param req
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/builder/getBaseTables")
	public void getBaseTables(HttpServletRequest req,
			HttpServletResponse response) throws IOException {
		List<Map<String, String>> result = TablesUtils.getBaseTables();
		JSONArray arrayObject = JSONArray.fromObject(result);
		String returnValue = arrayObject.toString();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		OutputStream stream = response.getOutputStream();
		stream.write(returnValue.getBytes("UTF-8"));
	}

	/**
	 * 获取当前的表字段信息
	 * 
	 * @param req
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/builder/getTableFields")
	public void getTableFields(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String tableName = request.getParameter("tableName");
		ITableFactory tableFactory = (ITableFactory) SpringBeanFactory
				.getBean("TableFactory");
		ITable pTable = tableFactory.openTable(tableName);
		Field[] fields = pTable.getFields();
		JSONArray arrayObject = JSONArray.fromObject(fields);
		String returnValue = arrayObject.toString();
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		OutputStream stream = response.getOutputStream();
		stream.write(returnValue.getBytes("UTF-8"));
	}

//	/**
//	 * 构建表单
//	 * 
//	 * @param req
//	 * @param response
//	 * @throws IOException
//	 * @throws TemplateException
//	 */
//	@RequestMapping(value = "/builder/builder")
//	public void builder(HttpServletRequest request, HttpServletResponse response)
//			throws IOException, TemplateException {
//		String formid = request.getParameter("formid");
//		IQueryMap queryMap = new QueryMap();
//		queryMap.getWhereMap().put(FormRow.PROP_FORMID, formid);
//		FormRow row = FormTable.getSingleRef().getEntity(FormRow.class,
//				queryMap);
//		if (row == null) {
//			return;
//		}
//		RelationOption.FillEntityChild(FormTable.getSingleRef(), row, true);
//
//		HashMap<String, Object> model = new HashMap<String, Object>();
//		String formTableName = row.getTableName();
//		model.put("tableName", formTableName);
//		ITable formTable = FormTable.getSingleRef().getTableFactory()
//				.openTable(formTableName);
//		model.put("guidField", formTable.getGUIDFieldName());
//		model.put("defulatValue", "null");
//		model.put("formName", row.getFormName());
//		model.put("newFormName", row.getShortFormName());
//
//		model.put("simpleSearchName", "全部模板");
//		model.put("simpleSearchField", "FLP_NAME");
//		model.put("simpleSearchDomainTable", "ECC_FORM_FORM");
//		model.put("simpleSearchDomainField", "FLP_NAME");
//
//		model.put("gridFields", row.getChildValues().get(GridTable.TABLE_NAME));
//		model.put("superSearchFields",
//				row.getChildValues().get(SupperSearchTable.TABLE_NAME));
//		model.put("formFields",
//				row.getChildValues().get(FormInfoTable.TABLE_NAME));
//
//		Configuration config = new Configuration();
//		ClassTemplateLoader ctl = new ClassTemplateLoader(this.getClass(), "/");
//		TemplateLoader tl = config.getTemplateLoader();
//		TemplateLoader[] loaders = new TemplateLoader[] { tl, ctl };
//		MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
//		config.setTemplateLoader(mtl);
//
//		Template t = null;
//		if (row.getFlpName().equals("1")) {
//			t = config.getTemplate("com/itfreer/builder/view/flt/form_flt.html");
//		} else if (row.getFlpName().equals("2")) {
//			t = config.getTemplate("com/itfreer/builder/view/flt/form_flt2.html");
//		} else if (row.getFlpName().equals("3")) {
//			t = config.getTemplate("com/itfreer/builder/view/flt/form_flt3.html");
//		} else {
//			t = config.getTemplate("com/itfreer/builder/view/flt/form_flt.html");
//		}
//
//		ByteArrayOutputStream os = new ByteArrayOutputStream();
//		OutputStreamWriter osw = new OutputStreamWriter(os);
//		t.process(model, osw);
//		String text = os.toString();
//		text = text.replace("^", "@").replace("`", "#").replace("~", "$");
//		String fileName = row.getFormPath();
//		fileName += "/" + row.getFormName() + ".html";
//
//		FileOutputStream fw = new FileOutputStream(fileName);
//		BufferedWriter bufferedWriter = new BufferedWriter(
//				new OutputStreamWriter(fw, "UTF-8"));
//		bufferedWriter.write(text);
//		bufferedWriter.flush();
//		bufferedWriter.close();
//	}

	@RequestMapping(value = "/builder/builderTables")
	public void builderTables(HttpServletRequest request,
			HttpServletResponse response) throws IOException, TemplateException {
		String JarName = request.getParameter("JarName");
		String ptah = request.getParameter("ptah");
		
		if (JarName == null || JarName.trim().equals("")) {
			JarName = "";
		}
		List<Map<String, String>> result = TablesUtils.getBaseTables();
		for (Map<String, String> item : result) {
			String tableid = item.get("id");
			innerBuilder(tableid, JarName, ptah);
		}
	}

	/**
	 * 构建表单
	 * 
	 * @param req
	 * @param response
	 * @throws IOException
	 * @throws TemplateException
	 */
	@RequestMapping(value = "/builder/builderTable")
	public void builderTable(HttpServletRequest request,
			HttpServletResponse response) throws IOException, TemplateException {
		String tableid = request.getParameter("table");
		String JarName = request.getParameter("JarName");
		String ptah = request.getParameter("ptah");
		if (JarName == null || JarName.trim().equals("")) {
			JarName = "";
		}

		innerBuilder(tableid, JarName, ptah);
	}

	private void innerBuilder(String tableid, String JarName, String ptah)
			throws IOException, TemplateException {
		IWorkspaceFactory workspaceFactory = (IWorkspaceFactory) SpringBeanFactory
				.getBean("WorkspaceFactory");
		IWorkspace pWorkspace = workspaceFactory.openWorkspace();
		ITableInfo tableInfo = pWorkspace.getTableMetadate(tableid);

		String tableName = tableid.trim();
		String[] tableNames = tableName.split("_");
		tableName = "";
		for (String tableNameItem : tableNames) {
			if (tableNameItem.trim() != "") {
				String first = tableNameItem.substring(0, 1);
				String other = tableNameItem.substring(1);
				tableName += first.toUpperCase() + other.toLowerCase();
			}
		}

		HashMap<String, Object> model = new HashMap<String, Object>();
		model.put("tableName", tableName);
		model.put("tableRealName", tableid.trim().toUpperCase());
		model.put("JarName", JarName);
		
		String hasGUID = "0";

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Field[] fields = tableInfo.getFields();
		for (Field f : fields) {
			Map<String, String> mapList = new HashMap<String, String>();

			String fieldName = f.getFieldName().trim();
			mapList.put("realFieldName", fieldName);
			if("GUID".equals(fieldName)){
				hasGUID = "1";
			}

			String[] fieldNames = fieldName.split("_");
			fieldName = "";
			for (String tableNameItem : fieldNames) {
				if (tableNameItem.trim() != "") {
					String first = tableNameItem.substring(0, 1);
					String other = tableNameItem.substring(1);
					fieldName += first.toUpperCase() + other.toLowerCase();
				}
			}
			mapList.put("isNullable",String.valueOf(f.getAllowNull()));
			mapList.put("fieldName", fieldName);
			mapList.put("dataType", f.getDataType().toString());
			if(f.getDataType()==GlobalDataType.String && f.getMaxLen()>0){
				mapList.put("maxLen", String.valueOf(f.getMaxLen()));
			}
			mapList.put("fieldAliasName", f.getFieldAliasName());
			list.add(mapList);
		}

		model.put("tableFields", list);
		model.put("hasGUID", hasGUID);

		Configuration config = new Configuration();
		ClassTemplateLoader ctl = new ClassTemplateLoader(this.getClass(), "/");
		TemplateLoader tl = config.getTemplateLoader();
		TemplateLoader[] loaders = new TemplateLoader[] { tl, ctl };
		MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
		config.setTemplateLoader(mtl);

		Template t = config
				.getTemplate("com/itfreer/form/view/flt/tables_flt.html");

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(os);
		t.process(model, osw);
		String text = os.toString();
		
		if(StringUtils.IsNullOrSpace(ptah)){
			ptah = "c:/builder/";
		}
		
		File dirFile = new File(ptah);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		String fileName = ptah + "/" + tableName + "Table.java";
		FileOutputStream fw = new FileOutputStream(fileName);

		BufferedWriter bufferedWriter = new BufferedWriter(
				new OutputStreamWriter(fw, "UTF-8"));
		bufferedWriter.write(text);
		bufferedWriter.flush();
		bufferedWriter.close();

		t = config.getTemplate("com/itfreer/form/view/flt/table_rows_flt.html");
		os = new ByteArrayOutputStream();
		osw = new OutputStreamWriter(os);
		t.process(model, osw);
		text = os.toString();

		fileName = ptah + "/" + tableName + "Row.java";
		fw = new FileOutputStream(fileName);
		bufferedWriter = new BufferedWriter(new OutputStreamWriter(fw, "UTF-8"));
		bufferedWriter.write(text);
		bufferedWriter.flush();
		bufferedWriter.close();
	}
}